package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.model.agent.UserCommunity;
import com.zbkj.common.model.agent.UserStoreRelation;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.OrderStoreRelation;
import com.zbkj.service.dao.OrderStoreRelationDao;
import com.zbkj.service.service.MerchantService;
import com.zbkj.service.service.OrderStoreRelationService;

import com.zbkj.common.request.OrderStoreRelationSaveRequest;
import com.zbkj.common.request.OrderStoreRelationSearchRequest;
import com.zbkj.common.response.OrderStoreRelationPageDataResponse;
import com.zbkj.common.response.OrderStoreRelationDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.service.service.UserCommunityService;
import com.zbkj.service.service.UserStoreRelationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author Caiyc
* @description OrderStoreRelationServiceImpl 接口实现
* @date 2025-07-28
*/
@Service
public class OrderStoreRelationServiceImpl extends ServiceImpl<OrderStoreRelationDao, OrderStoreRelation> implements OrderStoreRelationService {

    @Resource
    private OrderStoreRelationDao dao;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UserStoreRelationService userStoreRelationService;
    @Autowired
    private UserCommunityService userCommunityService;

    @Override
    public Boolean create(OrderStoreRelationSaveRequest orderStoreRelationSaveRequest) {
        OrderStoreRelation orderStoreRelation = new OrderStoreRelation();
        BeanUtils.copyProperties(orderStoreRelationSaveRequest, orderStoreRelation, "id");
        boolean save = save(orderStoreRelation);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询订单店铺关系表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<OrderStoreRelation>
     * @author Caiyc
     * @since 2025-07-28
     */
    @Override
    public List<OrderStoreRelationPageDataResponse> getList(OrderStoreRelationSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<OrderStoreRelation> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.orderByDesc(OrderStoreRelation::getCreateTime);
        List<OrderStoreRelation> orderStoreRelations = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<OrderStoreRelationPageDataResponse> orderStoreRelationResponses = new ArrayList<>();

        orderStoreRelations.stream().forEach(x->{
            OrderStoreRelationPageDataResponse orderStoreRelationResponse = new OrderStoreRelationPageDataResponse();
            BeanUtils.copyProperties(x, orderStoreRelationResponse);
            orderStoreRelationResponses.add(orderStoreRelationResponse);
        });
        return orderStoreRelationResponses;
    }

    /**
    * 修改订单店铺关系表
    * @param request
    * @return
    */
    @Override
    public boolean update(OrderStoreRelationSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入订单店铺关系表ID");
        }
        getByIdException(request.getId());
        OrderStoreRelation orderStoreRelation = new OrderStoreRelation();
        BeanUtils.copyProperties(request, orderStoreRelation);
        return updateById(orderStoreRelation);
    }

    private OrderStoreRelation getByIdException(Integer id) {
        OrderStoreRelation orderStoreRelation = getById(id);
        if (ObjectUtil.isNull(orderStoreRelation)) {
            throw new AppException("订单店铺关系表不存在");
        }
        if (orderStoreRelation.getIsDel()) {
            throw new AppException("订单店铺关系表不存在");
        }
        return orderStoreRelation;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
    LambdaUpdateWrapper<OrderStoreRelation> luw = Wrappers.lambdaUpdate();
        luw.set(OrderStoreRelation::getIsDel, true);
        luw.in(OrderStoreRelation::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除订单店铺关系表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public OrderStoreRelationDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<OrderStoreRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(OrderStoreRelation::getIsDel, 0);
        lqw.last("limit 1");
        OrderStoreRelation orderStoreRelation = this.getOne(lqw);
        if (ObjectUtil.isNotNull(orderStoreRelation)) {
            OrderStoreRelationDetailResponse response = new OrderStoreRelationDetailResponse();
            BeanUtils.copyProperties(orderStoreRelation, response);
            return response;
        }
        return null;
    }

    @Override
    public void updateOrderStoreRelation(String orderNo, Integer merId, Integer uid, List<OrderDetail> orderDetailList) {
        // 找到这个用户是否绑定了小区，有小区的时候订单才所属小区，没有小区订单就排除在外
        UserCommunity userCommunity = userCommunityService.getByUid(uid);
        if (userCommunity == null) {
            return;
        }
        UserStoreRelation userStoreRelation = userStoreRelationService.getByUid(uid);
        if (userStoreRelation == null) {
            // 上次没有从商家扫码，直接跳过
            return;
        }
        OrderStoreRelation orderStoreRelation = new OrderStoreRelation();
        orderStoreRelation.setOrderNo(orderNo);
        orderStoreRelation.setUserId(uid);
        orderStoreRelation.setCommunity(userStoreRelation.getCommunity());
        orderStoreRelation.setCommunityId(userStoreRelation.getCommunityId());

        if (userStoreRelation.getMerchantId().equals(merId)) {
            // 用户本店线上店铺下单，订单所属小区本店
            orderStoreRelation.setMerchantId(merId);
        } else {
            // 用户在别的店，浏览商品下单支付成功后，判断用户上次扫码的商户，记录订单号到这个商户id
            orderStoreRelation.setMerchantId(userStoreRelation.getMerchantId());
        }

        LambdaQueryWrapper<Merchant> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Merchant::getName, Merchant::getCommunity, Merchant::getCommunityId);
        wrapper.eq(Merchant::getId, merId);
        Merchant merchant = merchantService.getOne(wrapper);
        if (ObjectUtil.isNotNull(merchant)) {
            orderStoreRelation.setMerchantName(merchant.getName());
        }
        save(orderStoreRelation);
    }

}

